<?php
	//Never know when you'll need a session.
	session_start();
	//Some files...
	require_once 'adodb/adodb.inc.php';
	require_once 'adodb/adodb-exceptions.inc.php';

	//Functions
	function fixArr($array, $key) {
    	if(isset($array[$key])) {
        	return $array[$key];
    	}else{
        	return false;
    	}
	}

	//My file of classes
	class DbHandle {
		private static $instance = null;
		private $db;
		
		public static function getInstance(){
			if(!isset(self::$instance) || self::$instance == false){
				@self::$instance = NewADOConnection('mysql');
				@self::$instance->Connect('localhost', 'root', 'skings', 'monster');
			}else{
				self::$instance = false;
			}
			return self::$instance; //So what does this fancy feature do you might be asking yourself...well, basically, we can call this from outside the class without making a new class and it'll give us a database handler. We can also call it from inside the class and have the same effect, but basically it prevents the same instance from being called twice.
		}
		
		function __construct(){
			$this->db = $this->getInstance();
		}
	}
	
	class Administrator {
		private $adminID;
		private $username;
		private $password;
		private $cookie;
		private $db;
		private $isLogged;
        
        //Track the admin's moves
		public function adminGPS($action){
            $name = $this->username();
            $this->db->Execute("INSERT INTO `monster`.`adminEvents` (`AutoInc`, `Name`, `Action`, `Date`) VALUES (NULL, ?, ?, ?)", array($name, $action, time()));
            return true;
        }
        
		//Get the private variable username
		public function username() {
			return $this->username;
		}
		
		//Constructor
		public function __construct($db) {
			$this->db = $db;
		}
		
		//Tells whether or not the user is logged in
		public function isLogged() {
			return $this->isLogged;
		}
		
		//Log out...self explanitory. Destroy everything!
		public function logout() {
			if($this->isLogged() == false) return false;
			//Destroy a couple locals, not all of them. At least one is needed for ID.
			$this->adminGPS("Logged out.");
            $this->username = "";
			$this->password = "";
			$this->isLogged = false;
			//Destroy the session.
			session_destroy();
			//Erase the value from the database
			$this->db->Execute("UPDATE `monster`.`admins` SET `CookieInfo` = NULL WHERE `AutoInc` = ? LIMIT 1", array($this->adminID));
			//Destroy the last remaining value
			$this->adminID = -1;
			return true;
		}
		
		//Validate the user's current session/cookie
		public function validateLogin() {
			//Figure out if they have the session or the cookie...
			if(isset($_SESSION['ID'])) {
				$id = $_SESSION['ID'];
			}else if(isset($_COOKIE['ID'])) {
				$id = $_COOKIE['ID'];
			}else{
				$id = "";
			}
			//Use that ID to try to see if there's an admin with the same ID
			$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `CookieInfo` = ? LIMIT 1", array($id));
			//If there is then return true! Otherwise, false.
			if($sql->RecordCount() == 1) {
				$row = $sql->FetchRow();
				$this->username = $row['Name'];
				$this->password = $row['Password'];
				$this->adminID = $row['AutoInc'];
				$this->isLogged = true;
			}else{
				$this->isLogged = false;
			}
			return $this->isLogged();
		}
		
		//Login to the account
		public function login($username, $password, $rememberMe = false) {
			$username = trim($username);
			$password = trim($password);
			//Making sure we're not dealing with nothing
			if(empty($username) || empty($password)) return false;
			$password = $this->warpMyPassword($password);
			$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `Name` = ? AND `Password` = ? LIMIT 1", array($username, $password));
			if($sql->RecordCount() > 0) {
				$row = $sql->FetchRow();
				//Store local information
				$this->isLogged = true;
				$this->username = $username;
				$this->password = $password;
				$this->adminID = $row['AutoInc'];
				//Store the session
				$id = $this->warpMyPassword(rand(0, 10000));
				$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `CookieInfo` = ? LIMIT 1", array($id));
				while($sql->RecordCount() > 0) {
					//Ensures that this number is absolutely unique
					$id = $this->warpMyPassword(rand(0, 10000));
					$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `CookieInfo` = ? LIMIT 1", array($id));
				}
				//Make the database see the ID
				$this->db->Execute("UPDATE `monster`.`admins` SET `CookieInfo` = ?, `Last Login` = ? WHERE `AutoInc` = ? LIMIT 1", array($id, time(), $this->adminID));
				//Set the ID into a session
				$_SESSION['ID'] = $id;
				//If the user wants a cookie, we'll give them one.
				if($rememberMe) {
					//Creates a cookie that lasts 2 weeks
					setcookie("ID", $id, strtotime("+2 weeks"), "/");
				}
                $this->adminGPS("Logged in.");
				return true;
			}else{
				$this->isLogged = false;
				return false;
			}
			$this->isLogged = false;
			return false;
		}
		
		//Add a new user
		public function addAdmin($username, $password, $secQuestion, $secAnswer) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `Name` = ? LIMIT 1", array($username));
			if($sql->RecordCount() > 0) return false;
			if(strlen($password) < 6) return 0;
			$pass = $this->warpMyPassword($password);
			$this->db->Execute("INSERT INTO `monster`.`admins` (`AutoInc`, `Name`, `Password`, `CookieInfo`, `Last Login`, `SecurityQuestion`, `SecurityAnswer`) VALUES (NULL, ?, ?, NULL, NULL, ?, ?);", array($username, $pass, $secQuestion, $secAnswer)) or die($this->db->ErrorMsg());
			$this->adminGPS("Added an admin ({$username}) account.");
            return true;
		}
		
		//Edit a user
		public function editAdmin($newPassword, $oldPassword) {
			$oldPassword = $this->warpMyPassword($oldPassword);
			if($this->password != $oldPassword) return false;
			if(strlen($newPassword) < 6) return false;
			$pass = $this->warpMyPassword($newPassword);
			$sql = $this->db->Execute("UPDATE `monster`.`admins` SET `Password` = ? WHERE `AutoInc` = ? LIMIT 1", array($pass, $this->adminID));
			return true;
		}
		
		public function deleteAdmin($who) {
			if($this->adminExists($who)) {
                $this->adminGPS("Deleted admin {$who}.");
				return $this->db->Execute("DELETE FROM `monster`.`admins` WHERE `Name` = ? LIMIT 1", array($who));
            }
            return false;
		}
		
		//Recover the admin's password
		public function recoverPassword($who, $secAnswer) {
            $sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `Name` = ? AND `SecurityAnswer` = ? LIMIT 1", array($who, $secAnswer));
            if($sql->RecordCount() == 1){
                $password = substr($this->warpMyPassword(rand()), 0, 10);
                $password_warped = $this->warpMyPassword($password);
                $this->db->Execute("UPDATE `monster`.`admins` SET `Password` = ? WHERE `Name` = ? LIMIT 1", array($password_warped, $who));
                return $password;
            }else{
                return array("Error", "The answer entered was incorrect.");
            }
		}
		
		//Password hashing - super protection
		public function warpMyPassword($pass) {
			if($pass != null) {
				$salt1 = "0420dsojdljx02";
				$salt2 = "123michael19201";
				$salt3 = "milky201i80way";
				if(strlen($pass) > 1){
					$len = floor((strlen($pass) / 2));
					$first = substr($pass, 0, $len);
					$last = substr($pass, $len);
					$pass = $salt1.$first.$salt2.$last.$salt3;
				}else{
					$pass = $salt1.$pass.$salt3;
				}
				$pass = hash('sha512', $pass); //SHA is 128 characters long, by the way.
				$len = floor((strlen($pass) / 2));
					$pw = substr($pass, 0, $len);
				$pw = str_rot13($pw);
				$rest = substr($pass, $len);
				return($pw.$rest);
			}else{
				return false;
			}
		}
		
		public function adminExists($who) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`admins` WHERE `Name` = ? LIMIT 1", array($who));
			if($sql->RecordCount() == 1) return true;
			return false;
		}
	}
	
	class PrayerRequest {
		private $prayerRequestID;
		private $name;
		private $subject;
		private $message;
		private $isApproved;
		private $isApprovedBy;
		private $acc;
		private $db;
		
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Submit a prayer request
		public function submitPrayerRequest($name, $subject, $message, $email, $silent) {
			$name = trim($name);
			$subject = trim($subject);
			$message = trim($message);
			$email = trim($email);
            if($silent){
                $silent = 1;
            }else{
                $silent = 0;
            }
			$this->db->Execute("INSERT INTO `monster`.`prayers` (`AutoInc`, `Name`, `Subject`, `Message`, `Approved`, `Approved By`, `Email`, `Silent`) VALUES (NULL, ?, ?, ?, '0', NULL, ?, ?)", array($name, $subject, $message, $email, $silent));
		}
			
		//Approve a prayer request
		public function approvePrayerRequest($prayerRequestID) {
			$this->db->Execute("UPDATE `monster`.`prayers` SET `Approved` = \"1\" WHERE `AutoInc` = ? LIMIT 1", array($prayerRequestID));
            $this->acc->adminGPS("Approved prayer request #{$prayerRequestID}.");
			return true;
		}
		
		//Decline a prayer request
		public function declinePrayerRequest($prayerRequestID) {
			$this->deletePrayerRequest($prayerRequestID);
			$this->acc->adminGPS("Declined prayer request #{$prayerRequestID}.");
            return true;
		}
		
		//Delete an approved prayer request
		public function deletePrayerRequest($prayerRequestID) {
			$this->db->Execute("DELETE FROM `monster`.`prayers` WHERE `AutoInc` = ? LIMIT 1", array($prayerRequestID));
            $this->acc->adminGPS("Deleted prayer request #{$prayerRequestID}.");
			return true;
		}
		
		//List all prayer requests
		public function listPrayerRequests() {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`prayers` WHERE `Approved` = \"1\" AND `Silent` = '0' ORDER BY `prayers`.`AutoInc` ASC");
			if($sql->RecordCount() > 0){
				while($row = $sql->FetchRow()) {
					print "<b>{$row['Subject']}</b><br />\n\"{$row['Message']}\" - ".($row['Email'] != "" ? "<a href=\"mailto:{$row['Email']}\">{$row['Name']}</a>" : $row['Name'])."<br />\n<br />\n";
				}
			}else{
				print "Sorry, there are currently no prayer requests.";
			}
			return true;
		}
	}
	
	class Event {
		private $eventID;
		private $title;
		private $description;
		private $date;
		private $place;
		private $isApproved;
		private $approvedBy;
		private $acc;
		private $db;
		
		//Constructor
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Submit an event request
		public function submitEvent($title, $subject, $time, $place, $name = "", $phone = "", $email = "") {
			if($name == "" && $this->acc->isLogged()) $name = $this->acc->username;
			$this->db->Execute("INSERT INTO `monster`.`event` (`AutoInc`, `Title`, `Description`, `Date`, `DatePosted`, `Place`, `Approved`, `NameOfGuest`, `PhoneNumber`, `Email`) VALUES (NULL, ?, ?, ?, ?, ?, '0', ?, ?, ?)", array($title, $subject, $time, time(), $place, $name, $phone, $email));
			return true;
		}
		
		//Approve an event
		public function approveEvent($eventID) {
			if(!$this->getEventByID($eventID)) return false;
            $this->acc->adminGPS("Approved event #{$eventID}");
			$this->db->Execute("UPDATE `monster`.`event` SET `Approved` = \"1\" WHERE `AutoInc` = ? LIMIT 1", array($eventID));
			return true;
		}
		
		public function declineEvent($eventID) {
			return $this->deleteEvent($eventID);
		}
		
		//Post an event
		public function postEvent($title, $subject, $time, $place) {
            $this->acc->adminGPS("Posted event {$title}.");
			$this->db->Execute("INSERT INTO `monster`.`event` (`AutoInc`, `Title`, `Description`, `Date`, `DatePosted`, `Place`, `Approved`) VALUES (NULL, ?, ?, ?, ?, ?, '1')", array($title, $subject, $time, time(), $place));
			return true;
		}
		
		//Edit an event
		public function editEvent($eventID, $newTitle, $newSubject, $newTime, $newPlace) {
			if(!$this->getEventByID($eventID)) return false;
            $this->acc->adminGPS("Edited event {$newTitle}.");
			$this->db->Execute("UPDATE `monster`.`event` SET `Title` = ?, `Description` = ?, `Date` = ?, `Place` = ? WHERE `AutoInc` = ? LIMIT 1", array($newTitle, $newSubject, $newTime, $newPlace, $eventID));
			return true;
		}
		
		//Delete an event
		public function deleteEvent($eventID) {
			if(!$this->getEventByID($eventID)) return false;
            $this->acc->adminGPS("Deleted event #{$eventID}.");
			$this->db->Execute("DELETE FROM `monster`.`event` WHERE `AutoInc` = ? LIMIT 1", array($eventID));
			return true;
		}
		
		//Checks if an event exists on said day
		public function eventExistsOn($month, $day, $year) {
			$beginTime = strtotime($month." ".$day.", ".$year." 12:00 AM");
			$endTime = strtotime($month." ".$day.", ".$year." 11:59 PM");
			$sql = $this->db->Execute("SELECT * FROM `monster`.`event` WHERE `Date` > ? AND `Date` < ? AND `Approved` = '1' LIMIT 1", array($beginTime, $endTime));
			if($sql->RecordCount() == 1) {
				return true;
			}else{
				return false;
			}
		}
		
		//List all events
		public function listEvents() {
			//Generate calendar of events
			$todaysColor = "#cc3333";
			$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
			$month = fixArr($_GET, "month");
			$year = fixArr($_GET, "year");
			$_day = fixArr($_GET, "day");
			if(!$_day) $day = date('j');
			if(!$month) $month = date("F");
			if(!$year || !is_numeric($year)) $year = date("Y");
			if(strtolower($month) == $months[0]) {
				$_year = $year-1;
				$prevLink = "events.php?month={$months[count($months)-1]}&day={$_day}&year={$_year}";
			}else {
				$monthPlace = array_search(strtolower($month), $months);
				$monthPlace--;
				$prevLink = "events.php?month={$months[$monthPlace]}&day={$_day}&year={$year}";
			}
			if(strtolower($month) == $months[11]) {
				$_year = $year+1;
				$nextLink = "events.php?month={$months[0]}&day={$_day}&year={$_year}";
			}else{
				$monthPlace = array_search(strtolower($month), $months);
				$monthPlace++;
				$nextLink = "events.php?month={$months[$monthPlace]}&day={$_day}&year={$year}";
			}
			if($year > 2038) {
				return array("Error" => "I'm sorry, but the year 2038 is when Unix Timestamps become outdated and unusable. In order to use this calendar, you'll need to pick a date before that.");
			}else if($year < 1970) {
				return array("Error" => "I'm sorry, but the year 1970 is when Unix Timestamps were created. In order to use this calendar, you'll need to pick a date after that.");
			}
			if(!in_array(strtolower($month), $months)) $month = date("F");
			$time = strtotime("{$month} 1st, {$year}");
			$calendar = "<table width=\"130px\" style=\"font-size:12px\">\n<tr>\n<th colspan=\"7\"><a href=\"{$prevLink}\" style=\"text-decoration: none;\">&lt;</a>&nbsp;".ucwords($month)." {$year}&nbsp;<a href=\"{$nextLink}\" style=\"text-decoration: none;\">&gt;</a></th>\n</tr>\n<tr>\n<th>Su</th>\n<th>M</th>\n<th>Tu</th>\n<th>W</th>\n<th>Th</th>\n<th>F</th>\n<th>Sa</th>\n</tr>";
			$dayNum = date('w', $time);
			if($dayNum == 0) {
				if($this->eventExistsOn($month, date('j', $time), $year)) {
					$tr = "<tr>\n<td><a href=\"events.php?month={$month}&day=".date('j', $time)."&year={$year}\" style=\"font-weight: bold;\">1</a></td>\n";
				}else {
					$tr = "<tr>\n<td>1</td>\n";
				}
				$calendar .= $tr;
			}else {
				//print $dayNum;
				//die();
				$calendar .= "<tr>\n<td></td>\n";
				$i = 1;
				while($dayNum != $i) {
					$calendar .= "<td></td>\n";
					$i++;
				}
				if($year == date('Y') && $month == date('F') && 1 == date('j')) {
					$pre = "<span style=\"color: {$todaysColor}\">";
					$post = "</span>";
				}else {
					$pre = "";
					$post = "";
				}
				if($this->eventExistsOn($month, 1, $year)) {
					$tr = "<td><a href=\"events.php?month={$month}&day=1&year={$year}\" style=\"font-weight: bold;\">{$pre}1{$post}</a></td>\n";
				}else {
					$tr = "<td>{$pre}1{$post}</td>\n";
				}
				$calendar .= $tr;
				$i++;
			}
			$time += 86400; //24 hours
			$dayCounter = (isset($i) ? $i : 1);
			while(strtolower(date('F', $time)) == strtolower($month)) {
				if($dayCounter == 7) {
					$calendar .= "</tr>\n<tr>\n";
					$dayCounter = 0;
				}
				if($year == date('Y') && $month == date('F') && date('j', $time) == date('j')) {
					$pre = "<span style=\"color: {$todaysColor}\">";
					$post = "</span>";
				}else {
					$pre = "";
					$post = "";
				} 
				if($this->eventExistsOn($month, date('j', $time), $year)) {
					$tr = "<td><a href=\"events.php?month={$month}&day=".date('j', $time)."&year={$year}\" style=\"font-weight: bold;\">{$pre}".date('j', $time)."{$post}</a></td>\n";
				}else {
					$tr = "<td>{$pre}".date('j', $time)."{$post}</td>\n";
				}
				$calendar .= $tr;
				$time += 86400;
				$dayCounter++;
			}
			if($dayCounter != 0) {
				while($dayCounter < 7) {
					$calendar .= "<td></td>\n";
					$dayCounter++;
				}
				$calendar .= "</tr>\n";
			}
			return $calendar. "</table>";
		}
		
		//Get an event by ID
		public function getEventByID($id) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`event` WHERE `AutoInc` = ? LIMIT 1", array($id));
			$tool = array();
			if($sql->RecordCount() > 0) {
				$row = $sql->FetchRow();
				return $row;
			}
			return false;
		}
	}
	
	class PhotoAlbum {
		private $albumName;
		private $description;
		private $imageID;
		private $db;
		private $acc;
		
		//Runs when the class is initiated
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Add image to database
		public function addImage($pictureName, $imgLocation) {
			if(stristr($imgLocation, "http://") === false) return false;
            $this->acc->adminGPS("Added image {$pictureName} to database.");
			$this->db->Execute("INSERT INTO `monster`.`photos` (`AutoInc`, `Img Src`, `Name`) VALUES (NULL, ?, ?)", array($imgLocation, $pictureName));
			return true;
		}
		
		//Remove image from database
		public function removeImage($imageID) {
            $this->acc->adminGPS("Removed image #{$imageID} from database.");
			if(!$this->getImageByID($imageID)) return false;
			$this->db->Execute("DELETE FROM `monster`.`photos` WHERE `AutoInc` = ? LIMIT 1", array($imageID));
			return true;
		}
		
		//Edit image
		public function editImage($imageID, $newName, $newURL) {
			if(stristr($newURL, "http://") === false) return array("Error", "The image link was not valid.");
			if(!$this->getImageByID($imageID)) return array("Error", "The image ID is not valid.");
            $this->acc->adminGPS("Edited image {$newName}.");
			$this->db->Execute("UPDATE `monster`.`photos` SET `Img Src` = ?, `Name` = ? WHERE `AutoInc` = ? LIMIT 1", array($newURL, $newName, $imageID));
			return true;
		}
		
		//List all images
		public function listImages() {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`photos` ORDER BY `photos`.`AutoInc` ASC");
			if($sql->RecordCount() == 0) {
				print "I'm sorry, but we don't appear to have any images in our database right now.<br />\nPlease check again later.";
			}else{
				while($row = $sql->FetchRow()) {
					print "<a href=\"{$row['Img Src']}\" style=\"margin-right: 20px; padding-top: 30px;\"><img src=\"{$row['Img Src']}\" alt=\"{$row['Name']}\" width=\"150px\" height=\"100px\" /></a>\n";
				}
			}
			return true;
		}
		
		//Get an image by its ID
		public function getImageByID($id) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`photos` WHERE `AutoInc` = ? LIMIT 1", array($id));
			if($sql->RecordCount() > 0) return $sql->FetchRow();
			return false;
		}
	}
	
	class Need {
		private $needID;
		private $title;
		private $description;
		private $postedBy;
		private $db;
		private $acc;
		
		//Runs when the class is initiated
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Create a need request
		public function createNeedRequest($title, $description) {
			//Do something here
		}
		
		//Remove a need request
		public function deleteNeedRequest($donationID) {
			//Do something here
		}
		
		//Edit a need request
		public function editNeedRequest($donationID, $newTitle, $newDescription) {
			//Do something here
		}
		
		//Reply to need
		public function replyNeedRequest($donationID, $name, $message, $email) {
			//Do something here
		}
	}
	
	class Video {
		private $videoID;
		private $url;
		private $postedBy;
		private $acc;
		private $db;
		
		//Constructor
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Embed a new video
		public function addVideo($name, $url) {
            $this->acc->adminGPS("Added video {$name}.");
			$this->db->Execute("INSERT INTO `monster`.`videos` (`AutoInc`, `Name`, `Link`, `Posted By`) VALUES (NULL, ?, ?, ?)", array($name, $url, $this->acc->username()));
			return true;
		}
		
		//Remove a video
		public function removeVideo($videoID) {
			if(!$this->getVideoByID($videoID)) return false;
            $this->acc->adminGPS("Removed video #{$videoID}.");
			$this->db->Execute("DELETE FROM `monster`.`videos` WHERE `AutoInc` = ? LIMIT 1", array($videoID));
			return true;
		}
		
		//Change a video
		public function changeVideo($videoID, $name, $link) {
			if(!$this->getVideoByID($videoID)) return false;
            $this->acc->adminGPS("Changed video {$name}.");
			$this->db->Execute("UPDATE `monster`.`videos` SET `Name` = ?, `Link` = ?, `Posted By` = ? WHERE `AutoInc` = ? LIMIT 1", array($name, $link, $this->acc->username(), $videoID));
			return true;
		}
		
		//List the videos
		public function listVideos() {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`videos` ORDER BY `AutoInc` ASC");
			if($sql->RecordCount() > 0) {
				print "<span style=\"text-align: center;\">\n";
				while($row = $sql->FetchRow()) {
					print "<p>{$row['Name']}<br />\n";
					$_link = str_replace('watch?v=', 'v/', $row['Link']);
					//<object width="320" height="265"><param name="movie" value="http://www.youtube.com/v/YqMvuMRQypY&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/YqMvuMRQypY&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="265"></embed></object>
					print '<object width="320" height="265"><param name="movie" value="'.$_link.'&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$_link.'&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>';
					print "\n<br />\nPosted by {$row['Posted By']}</p>\n";
				}
				print "\n</span>";
			}else{
				print "I'm sorry, but at this time there are no videos in the database.";
			}
		}
		
		//Get a video by its ID
		public function getVideoByID($videoID) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`videos` WHERE `AutoInc` = ? LIMIT 1", array($videoID));
			if($sql->RecordCount() > 0){
				return $sql->FetchRow();
			}else{
				return false;
			}
		}
	}
	
	class BibleVerseOfTheWeek {
		private $bibleVerseOfTheWeekID;
		private $verse;
		private $text;
		private $datePosted;
		private $postedBy;
		private $acc;
		private $db;
		
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Add a Bible verse
    public function addBibleVerse($verse, $text, $date){
        if($verse == "") return array("Error", "The verse was left empty.");
        if($text == "") return array("Error", "The text was left empty.");
        $time = strtotime($date." 12:00 AM");
        if($time < time()) return array("Error", "The date selected was invalid.");
        $sql = $this->db->Execute("SELECT * FROM `monster`.`prayerOfWeek` WHERE `Date` = ? LIMIT 1", array($time));
        if($sql->RecordCount() == 1) return array("Error", "A prayer on this date already exists. You'll have to edit the already existing one if this is the date you meant to choose.");
        $this->acc->adminGPS("Added bible verse {$verse}.");
        $this->db->Execute("INSERT INTO `monster`.`prayerOfWeek` (`AutoInc`, `Verse`, `Text`, `Date`) VALUES (NULL, ?, ?, ?);", array($verse, $text, $time));
        return true;
    }
		
		//Edit a Bible verse
		public function editBibleVerse($bibleVerseOfTheWeekID, $verse, $text, $date) {
        if($verse == "") return array("Error", "The verse was left empty.");
        if($text == "") return array("Error", "The text was left empty.");
        $time = strtotime($date." 12:00 AM");
        if($time < time()) return array("Error", "The date selected was invalid.");
        $sql = $this->db->Execute("SELECT * FROM `monster`.`prayerOfWeek` WHERE `Date` = ? LIMIT 1", array($time));
        if($sql->RecordCount() == 1) return array("Error", "A prayer on this date already exists. You'll have to edit the already existing one if this is the date you meant to choose.");
        if(!$this->getBibleVerseByID($bibleVerseOfTheWeekID)) return array("Error", "A prayer with this ID does not exist.");
        $this->acc->adminGPS("Edited bible verse {$verse}.");
        $this->db->Execute("UPDATE `monster`.`prayerOfWeek` SET `Verse` = ?, `Date` = ?, `Text` = ? WHERE `AutoInc` = ? LIMIT 1", array($verse, $time, $text, $bibleVerseOfTheWeekID));
        return true;
		}
		
		//Remove a Bible verse
		public function removeBibleVerse($bibleVerseOfTheWeekID) {
			if(!$this->getBibleVerseByID($bibleVerseOfTheWeekID)) return array("Error", "A verse with this ID does not exist.");
            $this->acc->adminGPS("Removed bible version #{$bibleVerseOfTheWeekID}.");
            $this->db->Execute("DELETE FROM `monster`.`prayerOfWeek` WHERE `AutoInc` = ? LIMIT 1", array($bibleVerseOfTheWeekID));
            return true;
		}
		
		//Get a Bible verse by its ID
		public function getBibleVerseByID($bibleVerseOfTheWeekID) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`prayerOfWeek` WHERE `AutoInc` = ? LIMIT 1", array($bibleVerseOfTheWeekID));
            if($sql->RecordCount() == 1) return $sql->FetchRow();
            return false;
		}
	}
	
	class Sponsor {
		private $sponsorID;
		private $name;
		private $description;
		private $url;
		private $logo;
		private $approvedBy;
		private $db;
		private $acc;
		
		//Runs when the class is initiated
		public function __construct($acc, $db) {
			$this->acc = $acc;
			$this->db = $db;
		}
		
		//Add a sponsor
		public function addSponsor($name, $description, $url, $logo) {
			if($this->sponsorExistsByName($name)) return array("Error", "A sponsor with this name exists.");
			if(stristr($url, "http://") === false && !empty($url)) return array("Error", "The link to the sponsor is not valid.");
			if(stristr($logo, "http://") === false && !empty($logo)) return array("Error", "The sponsor logo link is not valid.");
			if(empty($description)) return array("Error", "The sponsor description was left empty.");
            $this->acc->adminGPS("Added sponsor {$name}.");
			$this->db->Execute("INSERT INTO `monster`.`sponsors` (`AutoInc`, `Sponsor Name`, `Sponsor Description`, `Sponsor Link`, `Sponsor Logo`) VALUES (NULL, ?, ?, ?, ?)", array($name, $description, $url, $logo));
			return true;
		}
		
		//Edit a sponsor
		public function editSponsor($sponsorID, $name, $description, $url, $logo) {
			if($this->getSponsorByID($sponsorID) == false) return array("Error", "A sponsor by this ID does not exist.");
			if(stristr($url, "http://") === false && !empty($url)) return array("Error", "The link to the sponsor is not valid.");
			if(stristr($logo, "http://") === false && !empty($logo)) return array("Error", "The sponsor logo link is not valid.");
			if(empty($description)) return array("Error", "The sponsor description was left empty.");
            $this->acc->adminGPS("Edited sponsor {$name}.");
			$this->db->Execute("UPDATE `monster`.`sponsors` SET `Sponsor Name` = ?, `Sponsor Link` = ?, `Sponsor Logo` = ?, `Sponsor Description` = ? WHERE `AutoInc` = ? LIMIT 1", array($name, $url, $logo, $description, $sponsorID));
			return true;
		}
		
		//Remove a sponsor
		public function removeSponsor($sponsorID) {
			if(!$this->getSponsorByID($sponsorID)) return false;
            $this->acc->adminGPS("Removed sponsor #{$sponsorID}.");
            $this->db->Execute("DELETE FROM `monster`.`sponsors` WHERE `AutoInc` = ? LIMIT 1", array($sponsorID));
            return true;
		}
		
		//Tells if a sponsor with this name exists
		public function sponsorExistsByName($sponsorName) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`sponsors` WHERE `Sponsor Name` = ? LIMIT 1", array($sponsorName));
			if($sql->RecordCount() > 0) return true;
			return false;
		}
		
		//Returns the sponsor infromation
		public function getSponsorByID($id) {
			$sql = $this->db->Execute("SELECT * FROM `monster`.`sponsors` WHERE `AutoInc` = ? LIMIT 1", array($id));
			if($sql->RecordCount() > 0) return $sql->FetchRow();
			return false;
		}
	
		//List all sponsors
		public function listSponsors() {
			//Get the list of sponsor
			$sql = $this->db->Execute("SELECT * FROM `monster`.`sponsors` ORDER BY `sponsors`.`Sponsor Name` ASC");
			if($sql->RecordCount() > 0) {
				while($row = $sql->FetchRow()){
					print "<br />\n".$row['Sponsor Name']."<br />\n";
					if($row['Sponsor Logo'] != "") {
						$link = "#";
						if($row["Sponsor Link"] != "") $link = $row['Sponsor Link'];
						print "<a href=\"{$link}\"><img src=\"{$row['Sponsor Logo']}\" alt=\"{$row['Sponsor Name']}\" /></a><br />\n";
					}
					print "<b>Description</b>: {$row['Sponsor Description']}<br />\n";
					if($row['Sponsor Link'] != "") {
						print "<b>Website</b>: <a href=\"{$row['Sponsor Link']}\">{$row['Sponsor Link']}</a><br />\n";
					}
				}
			}else{
				print "At this time there are no sponsors to be listed.";
			}
		}
	}
	
	function change_site($w_site) {
		return '<script type="text/javascript">window.location = "'.$w_site.'";</script>
		<noscript>
		<meta http-equiv=\'refresh\' content=\'0;url='.$w_site.'\'/>
		</noscript>';
	}
?>